package com.mcptt.config;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.JDOMException;

import android.content.Context;

import com.cloudptt.api.comm.Const;
import com.cloudptt.api.product.func.addr.IAddrDefaultOp;
import com.cloudptt.api.product.func.call.CallAttr;
import com.cloudptt.api.product.log.Log;
import com.mcptt.config.callback.IParserCallback;
import com.mcptt.config.group.Group;
import com.mcptt.config.local.SysConfig;
import com.mcptt.config.model.BootStrapSvrInfo;
import com.mcptt.config.model.McIdInfo;
import com.mcptt.config.service.Service;
import com.mcptt.config.ue.config.UeConfig;
import com.mcptt.config.ue.initial.UeInitProfile;
import com.mcptt.config.user.profile.UserProfile;
import com.mcptt.db.DBAdapter;
import com.mcptt.db.model.SessionInfo;
import com.mcptt.db.model.UserInfo;
import com.mcptt.notify.presence.Affiliation;
import com.mcptt.notify.presence.PresenceParser;
import com.mcptt.notify.xcap.XcapDoc;
import com.mcptt.notify.xcap.XcapParser;

public class ConfigFilesManager
{
	private UeInitProfile ueInitProfile = null;
	private UserProfile userProfile_Mcptt = null;
	private UserProfile userProfile_Mcvideo = null;
	private UserProfile userProfile_Mcdata = null;
	private Service service = null;
	private UeConfig ueProfile = null;
	private Map<String,Group> groupConfigMap = null;

	private DBAdapter dbAdapter = null;
	private SysConfig sysConfig = null;
	private McIdInfo mcIdInfo = null;
	private IAddrDefaultOp addrDefaultOp = null;


	public ConfigFilesManager(Context ctx, DBAdapter dbAdapter, SysConfig sysConfig, IAddrDefaultOp addrDefaultOp)
	{
		Log.debug(this.getClass(), "ConfigFilesManager");
		this.dbAdapter = dbAdapter;
		this.sysConfig = sysConfig;
		this.addrDefaultOp = addrDefaultOp;

		groupConfigMap = new HashMap<String,Group>();

		cleanOldPresence();
	}

	public void updateMcIdInfo(McIdInfo mcIdInfo)
	{
		this.mcIdInfo = mcIdInfo;
	}


	public void initUeInitProfile(String clientId, IParserCallback parserCallBack)
	{
		this.ueInitProfile = new UeInitProfile(dbAdapter,sysConfig.getBootStrapSvr(),clientId,parserCallBack);
//		if(ueInitProfile == null)
//		{
//			parserCallBack.parserFileFailed(UeInitProfile.FileName, "ueInitProfile = null");
//		}
//		else
//		{
//			Log.debug(this.getClass(), "initUesInitProfile ueInitProfile != null");
//			parserCallBack.parserFileSuc(UeInitProfile.FileName);
//		}
//		StringBuffer strBuf = new StringBuffer();
//		strBuf.append("--------UeInitProfile--------").append("\r\n");
//		strBuf.append(ueInitProfile.toString());
//		Log.debug(this.getClass(), ueInitProfile.toString());
		//		service = new Service(dbOperatorManager.getConfigDbOperator(),initCallBack);
	}

	public void initUeInitProfileForMcId(String mcId, IParserCallback parserCallBack)
	{
		Log.debug(this.getClass(),  "initUeInitProfileForMcId mcId = " + mcId);
//		this.ueInitProfile = new UeInitProfile(dbAdapter,sysConfig.getBootStrapSvr(),clientId,parserCallBack);
		this.ueInitProfile = new UeInitProfile(dbAdapter,sysConfig.getBootStrapSvr(),mcId,parserCallBack);
//		if(ueInitProfile == null)
//		{
//			parserCallBack.parserFileFailed(UeInitProfile.FileName, "ueInitProfile = null");
//		}
//		else
//		{
//			Log.debug(this.getClass(), "initUesInitProfile ueInitProfile != null");
//			parserCallBack.parserFileSuc(UeInitProfile.FileName);
//		}
//		StringBuffer strBuf = new StringBuffer();
//		strBuf.append("--------UeInitProfile--------").append("\r\n");
//		strBuf.append(ueInitProfile.toString());
//		Log.debug(this.getClass(), ueInitProfile.toString());
		//		service = new Service(dbOperatorManager.getConfigDbOperator(),initCallBack);
	}

//	public void getUserProfile(int mcType, IParserCallback parserCallBack)
//	{
//		if(CallAttr.McType_McVideo == mcType)
//		{
//			this.userProfile_Mcvideo = new UserProfile(mcType,mcIdInfo,dbAdapter,sysConfig,parserCallBack,addrDefaultOp);
//		}
//		else if(CallAttr.McType_McData == mcType)
//		{
//			this.userProfile_Mcdata = new UserProfile(mcType,mcIdInfo,dbAdapter,sysConfig,parserCallBack,addrDefaultOp);
//		}
//		else
//		{
//			this.userProfile_Mcptt = new UserProfile(mcType,mcIdInfo,dbAdapter,sysConfig,parserCallBack,addrDefaultOp);
//		}
//	}


	public void recvXcapNotify(String cmsUrl,String gmsUrl,String notifyStr,String accessToken,IParserCallback parserCallback)
	{
		Log.debug(getClass(), "recvXcapNotify cmsUrl = " + cmsUrl + " gmsUrl = " + gmsUrl + " notifyStr = " + notifyStr + " accessToken = " + accessToken);
		XcapParser parser = new XcapParser();
		try
		{
			parser.parse(notifyStr);
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			notifyXcapFailed(parserCallback,null,e.getClass().getSimpleName());
		} catch (JDOMException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			notifyXcapFailed(parserCallback,null,e.getClass().getSimpleName());
		}

		//	String accessToken = getLocalConfig().getAccessToken();
//		Log.debug(getClass(), "accessToken = " + accessToken);
		List<XcapDoc> docList = parser.getDocList();
		if(docList == null
				|| docList.size() <= 0)
		{
			notifyXcapFailed(parserCallback,null,"list.size() <= 0");
			return;
		}
//		String rootPath = cmsUrl + parser.getRoot();
		String rootPath = sysConfig.getBootStrapSvr().getCmsHttpUrl();//parser.getRoot();
		Log.debug(getClass(), "recvXcapNotify docList = " + docList.size());
		for(Iterator<XcapDoc> itor = docList.iterator();itor.hasNext();)
		{
			XcapDoc doc = itor.next();
			readFromSvr(doc, rootPath, gmsUrl,accessToken,parserCallback);
		}
	}

	public void cleanOldPresence()
	{
		Log.debug(getClass(), "cleanOldPresence");
		//		if(groupConfigMap == null
		//				|| groupConfigMap.size() <= 0)
		//		{
		//			return;
		//		}
		//		else
		//		{
		//			for(Iterator<String> itor = groupConfigMap.keySet().iterator();itor.hasNext();)
		//			{
		//				String groupNum = itor.next();
		//				this.dbOperatorManager.getDbOperator().getHistoryDbOperator().delAffiliationSession();
		//			}
//		this.dbAdapter.delAffiliationSession();
		//		if(parserCallback != null)
		//		{
		//			parserCallback.initialSuc("Presence clean");
		//		}
		//		}
	}
	public void recvPresenceNotify(String notifyStr,IParserCallback parserCallback)
	{
		Log.debug(getClass(), "recvPresenceNotify notifyStr = " + notifyStr);
		PresenceParser parser = new PresenceParser();
		try
		{
			parser.parse(notifyStr);
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			notifyPresenceFailed(parserCallback,null,e.getClass().getSimpleName());
		} catch (JDOMException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			notifyPresenceFailed(parserCallback,null,e.getClass().getSimpleName());
		}
		String mcpttId = parser.getEntity();
		List<Affiliation> list = parser.getAffiliationList();
		if(list == null
				|| list.size() <= 0)
		{
			notifyXcapFailed(parserCallback,null,"list.size() <= 0");
		}
		else
		{
			for(Iterator<Affiliation> itor = list.iterator();itor.hasNext();)
			{
				Affiliation af = itor.next();
				boolean isValid = af.isValid();
				Log.debug(getClass(), "recvPresenceNotify group = " + af.getGroup() + " isValid = " + isValid);
				if(isValid)
				{
//					UserInfo groupInfo = af.toUserInfo();
////					this.dbAdapter.updateUser(groupInfo);
//					SessionInfo info = af.toSessionInfo(groupInfo,mcpttId);
//					this.dbAdapter.insertNewSession(info, false);

				}
			}
			if(parserCallback != null)
			{
				parserCallback.parserFileSuc("Presence");
			}
		}
	}


	public void readFromSvr(XcapDoc doc,String rootPath,String gmsUrl,String accessToken,IParserCallback parserCallback)
	{
		Log.debug(getClass(), "readFromSvr doc.getFileName() = " + doc.getFileName() + " rootPath = " + rootPath + " gmsUrl = " + gmsUrl );
		AbstractConfigFile configFile = null;

		String fileName = doc.getFileName();
		Log.debug(getClass(), "readFromSvr fileName = " + fileName);
		if(UeInitProfile.FileName.equals(fileName))
		{
			//	    configFile = 
		}
		else if(UeConfig.FileName.equals(fileName))
		{
			ueProfile = new UeConfig(dbAdapter,parserCallback);
			configFile = ueProfile;
		}
		else if(UserProfile.FileName_Mcptt.equals(fileName))
		{
			userProfile_Mcptt = new UserProfile(UserInfo.McType_Ptt,mcIdInfo,dbAdapter,sysConfig,parserCallback,addrDefaultOp);
			configFile = userProfile_Mcptt;
		}
		else if(UserProfile.FileName_Mcvideo.equals(fileName))
		{
			userProfile_Mcvideo = new UserProfile(UserInfo.McType_Video,mcIdInfo,dbAdapter,sysConfig,parserCallback,addrDefaultOp);
			configFile = userProfile_Mcvideo;
		}
		else if(UserProfile.FileName_Mcdata.equals(fileName))
		{
			userProfile_Mcdata = new UserProfile(UserInfo.McType_Data,mcIdInfo,dbAdapter,sysConfig,parserCallback,addrDefaultOp);
			configFile = userProfile_Mcdata;
		}
//		else if(Service.FileName.equals(fileName))
//		{
//			service = new Service(dbAdapter,parserCallback);
//			configFile = service;
//		}
		if(configFile != null)
		{
			//	    configFile.readFromSvr(doc, rootPath, accessToken,parserCallback);
			configFile.runReadFromSvrThread(doc, rootPath, accessToken, parserCallback);
		}
		else
		{
			if(!Group.FileName_Mcptt.equals(fileName)
					&& !Group.FileName_Mcvideo.equals(fileName)
					&& !Group.FileName_Mcdata.equals(fileName))
			{
				Log.debug(getClass(), "readFromSvr configFile = null");
				notifyXcapFailed(parserCallback,fileName,"readFromSvr configFile = null");
			}
		}
		if(Group.FileName_Mcptt.equals(fileName))
		{
			String groupName = fileName + "_" + doc.getGroupName();
			Log.debug(getClass(), "readFromSvr groupName = " + groupName);
			Group group = new Group(UserInfo.McType_Ptt,dbAdapter,groupName,parserCallback);
			if(group != null)
			{
				group.runReadFromSvrThread(doc, rootPath, accessToken,parserCallback);
//				group.runReadFromSvrThread(doc, gmsUrl, accessToken, parserCallback);
				groupConfigMap.put(groupName, group);
			}
			else
			{
				Log.debug(getClass(), "readFromSvr group = null");
				notifyXcapFailed(parserCallback,fileName,"readFromSvr group = null");
			}
		}
		else if(Group.FileName_Mcvideo.equals(fileName))
		{
			String groupName = fileName + "_" + doc.getGroupName();
			Log.debug(getClass(), "readFromSvr groupName = " + groupName);
			Group group = new Group(UserInfo.McType_Video,dbAdapter,groupName,parserCallback);
			if(group != null)
			{
				//		group.readFromSvr(doc, rootPath, accessToken,parserCallback);
				group.runReadFromSvrThread(doc, gmsUrl, accessToken, parserCallback);
				groupConfigMap.put(groupName, group);
			}
			else
			{
				Log.debug(getClass(), "readFromSvr group = null");
				notifyXcapFailed(parserCallback,fileName,"readFromSvr group = null");
			}
		}
		else if(Group.FileName_Mcdata.equals(fileName))
		{
			String groupName = fileName + "_" + doc.getGroupName();
			Log.debug(getClass(), "readFromSvr groupName = " + groupName);
			Group group = new Group(UserInfo.McType_Data,dbAdapter,groupName,parserCallback);
			if(group != null)
			{
				//		group.readFromSvr(doc, rootPath, accessToken,parserCallback);
				group.runReadFromSvrThread(doc, gmsUrl, accessToken, parserCallback);
				groupConfigMap.put(groupName, group);
			}
			else
			{
				Log.debug(getClass(), "readFromSvr group = null");
				notifyXcapFailed(parserCallback,fileName,"readFromSvr group = null");
			}
		}
	}

	//	private void notifyInitFailed(IInitCallback callback,String errStr)
	//	{
	//		if(callback != null)
	//		{
	//			callback.initUsrProfileFailed(errStr);
	//		}
	//	}

	private void notifyXcapFailed(IParserCallback parserCallback,String fileName,String errStr)
	{
		if(parserCallback != null)
		{
			parserCallback.parserFileFailed(fileName,"recvXcapNotify " + errStr);
		}
	}
	private void notifyPresenceFailed(IParserCallback parserCallback,String fileName,String errStr)
	{
		if(parserCallback != null)
		{
			parserCallback.parserFileFailed(fileName,"recvXcapNotify " + errStr);
		}
	}

	public AbstractConfigFile getConfigFileByFileType(String fileName)
	{
		Log.debug(getClass(), "getConfigFileByFileType fileName = " + fileName + "UeInitProfile.FileName = " + UeInitProfile.FileName);
		if(UeInitProfile.FileName.equals(fileName))
		{
			Log.debug(getClass(), "getConfigFileByFileType ueInitProfile = " + ueInitProfile);
			return ueInitProfile;
		}
		else if(UeConfig.FileName.equals(fileName))
		{
			return ueProfile;
		}
		else if(UserProfile.FileName_Mcptt.equals(fileName))
		{
			return userProfile_Mcptt;
		}
		else if(UserProfile.FileName_Mcvideo.equals(fileName))
		{
			return userProfile_Mcvideo;
		}
		else if(UserProfile.FileName_Mcdata.equals(fileName))
		{
			return userProfile_Mcdata;
		}
		else if(Service.FileName.equals(fileName))
		{
			return service;
		}
		return null;
	}

	public Group getGroupConfigFileByGroupName(String groupName)
	{
		if(groupConfigMap != null
				&& groupConfigMap.size() > 0)
		{
			return groupConfigMap.get(groupName);
		}

		return null;
	}
}
